<template>
  <div class="avatar-upload">
    <!-- 预览模式 -->
    <div class="preview" v-if="previewUrl">
      <img :src="previewUrl" alt="头像预览" />
      <div class="action-buttons">
        <van-button type="primary" size="small" @click="confirmUpload">保存</van-button>
        <van-button plain size="small" @click="cancelUpload">取消</van-button>
      </div>
    </div>
    <!-- 显示模式 - 只显示原始头像 -->
    <div v-else class="avatar-display">
      <div class="avatar-wrapper">
        <van-uploader :after-read="afterRead" accept="image/*">
          <div class="upload-trigger original">
            <img 
              :src="processImageUrl(props.avatarUrl) || getDefaultAvatarUrl()" 
              alt="原始头像" 
              @error="handleImageError" 
              class="avatar-img"
            />
            <div class="overlay">
              <van-icon name="photograph" size="24" />
              <span>点击更新头像</span>
            </div>
          </div>
        </van-uploader>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { showSuccessToast, showFailToast } from 'vant';
import myAxios from '../plugins/myAxios';
import { processImageUrl } from '../utils/imageUtils';

const props = defineProps({
  avatarUrl: String
});

const emit = defineEmits(['update:avatarUrl']);

const previewUrl = ref('');
const fileToUpload = ref<File | null>(null);
const uploadInProgress = ref(false);
const uploadTimestamp = ref(0);
const uploadCooldown = 3000; // 3秒冷却时间
const imageLoaded = ref(false);

// 图片加载错误处理函数
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  console.error('图片加载失败:', target.src);
  target.src = getDefaultAvatarUrl();
  target.onerror = null; // 防止循环触发错误
};

// 获取默认头像URL
const getDefaultAvatarUrl = () => {
  return '/src/assets/defaultAvatar.png';
};

// 监听URL变化
watch(() => props.avatarUrl, (newUrl) => {
  console.log('头像URL已更新:', newUrl);
  if (newUrl) {
    console.log('处理后的头像URL:', processImageUrl(newUrl));
  }
}, { immediate: true });

// 在组件挂载时检查头像URL
onMounted(() => {
  console.log('头像组件已挂载');
  console.log('头像URL:', props.avatarUrl);
  
  // 检查当前头像URL是否有效
  if (props.avatarUrl) {
    const processedUrl = processImageUrl(props.avatarUrl);
    console.log('处理后的头像URL:', processedUrl);
    const img = new Image();
    img.onload = () => {
      console.log('头像加载成功');
      imageLoaded.value = true;
    };
    img.onerror = () => {
      console.log('头像加载失败，使用默认头像');
    };
    img.src = processedUrl;
  }
});

interface FileAfterRead {
  content: string;
  file: File;
}

// 选择文件后的预览
const afterRead = (file: FileAfterRead) => {
  previewUrl.value = file.content;
  fileToUpload.value = file.file;
};

// 检查上传冷却时间
const checkUploadCooldown = (): boolean => {
  const now = Date.now();
  const timeSinceLastUpload = now - uploadTimestamp.value;
  
  if (timeSinceLastUpload < uploadCooldown) {
    const waitTime = Math.ceil((uploadCooldown - timeSinceLastUpload) / 1000);
    showFailToast(`请求过于频繁，请等待${waitTime}秒后再试`);
    return false;
  }
  
  return true;
};

// 处理上传错误
const handleUploadError = (error: any) => {
  console.error('上传过程中发生错误:', error);
  
  // 根据错误类型提供更友好的提示
  if (error.code === 'ECONNABORTED') {
    showFailToast('上传超时，请检查网络连接或稍后重试');
  } else if (error.response) {
    showFailToast(`上传失败: ${error.response.data?.message || '服务器错误'}`);
  } else if (!navigator.onLine) {
    showFailToast('网络连接已断开，请检查网络设置');
  } else {
    showFailToast('上传失败，请稍后重试');
  }
};

// 检查头像URL是否可访问
const checkAvatarUrl = async (imageUrl: string) => {
  try {
    const checkResponse: any = await myAxios.post('/image/check-url', {
      imageUrl: imageUrl
    });
    
    if (checkResponse.code === 0) {
      console.log('图片URL检查结果:', checkResponse.data);
      
      // 根据检查结果判断URL是否可访问
      if (checkResponse.data.storage_type === '未知或外部URL') {
        console.warn('警告: 头像URL可能无法正确访问');
        showFailToast('头像可能无法正确显示，请重新上传');
      }
    }
  } catch (error) {
    console.error('检查头像URL失败', error);
  }
};

// 确认上传
const confirmUpload = async () => {
  // 初始验证
  if (!fileToUpload.value || uploadInProgress.value) {
    return;
  }
  
  // 检查冷却时间
  if (!checkUploadCooldown()) {
    return;
  }
  
  // 准备上传
  uploadInProgress.value = true;
  uploadTimestamp.value = Date.now();
  
  const formData = new FormData();
  formData.append('file', fileToUpload.value);
  
  try {
    const res: any = await myAxios.post('/image/avatar/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 30000 // 增加超时时间到30秒，因为上传图片可能需要更长时间
    });
    
    if (res.code === 0) {
      showSuccessToast('头像上传成功');
      
      // 检查一下上传的URL
      console.log('服务器返回的头像URL:', res.data);
      
      // 将URL更新到父组件
      emit('update:avatarUrl', res.data);
      previewUrl.value = '';
      fileToUpload.value = null;
      
      // 检查URL是否可访问
      await checkAvatarUrl(res.data);
    } else if (res.code === 42900) {
      showFailToast({
        message: '头像上传频率受限，请稍后再试',
        position: 'bottom',
        duration: 5000
      });
    } else {
      showFailToast(res.description || '上传失败');
    }
  } catch (error) {
    handleUploadError(error);
  } finally {
    uploadInProgress.value = false;
  }
};

// 取消上传
const cancelUpload = () => {
  previewUrl.value = '';
  fileToUpload.value = null;
  uploadInProgress.value = false;
};
</script>

<style scoped>
.avatar-upload {
  text-align: right;
  margin-right: 10px;
}

.avatar-display {
  display: flex;
  justify-content: flex-end;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-trigger {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.upload-trigger:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  transform: translateY(-2px);
}

.upload-trigger img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.upload-trigger .overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
}

.upload-trigger:hover .overlay {
  opacity: 1;
}

.upload-trigger.original {
  border: 2px solid #1989fa;
}

.avatar-img {
  transition: opacity 0.3s;
}

.avatar-img[src=""] {
  opacity: 0;
}

.preview {
  text-align: right;
}

.preview img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 10px;
  margin-left: auto;
  display: block;
  border: 2px solid #1989fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 10px;
}
</style> 